import os
import sys
from time import sleep

from selenium.common.exceptions import NoSuchElementException
import xlrd
from xlrd import open_workbook
from xlutils.copy import copy

from common import settings
from common.settings import JS_DIR, DATA_DIR
from common.decorators import log4gs

@log4gs
def save_screenshot(obj, filename):
    """
    保存屏幕截图
    :param obj: self
    :param filename: 截图名称
    :return:
    """
    ver = settings.TAG
    classname = obj.__class__.__name__
    case_name = sys._getframe(1).f_code.co_name
    linenum = sys._getframe(1).f_lineno
    file_name = case_name + '_' + str(linenum) + '_' + filename + '.png'
    file_path = os.path.join(settings.SCREENSHOT_DIR, ver, classname, file_name)
    try:
        obj.page.driver.save_screenshot(file_path)
        save_screenshot.log.info('截图成功：{}'.format(file_path))
    except Exception:
        save_screenshot.log.error('截图失败：{}'.format(file_path), exc_info=True)


def get_xpath(driver, btn):
    with open(os.path.join(JS_DIR, 'getXpath'), 'r', encoding='utf-8') as fp:  # 这里文件不用后缀名
        return driver.execute_script(fp.read(), btn)


@log4gs
def has_text_wait(elem, timeout=5, interval=0.5):
    """
    等待元素里面出现文本
    :param elem: 需要寻找文本的元素
    :param timeout: 查找的总时间
    :param interval: 每次查找间隔
    :return:
    """
    wait = 0
    text = elem.text
    try:
        while not text:
            wait += interval
            sleep(interval)
            text = elem.text
            if text:
                return
            elif wait > timeout:
                raise NoSuchElementException("5秒没出现文本")
    except NoSuchElementException:
        has_text_wait.log.error("5秒没出现文本", exc_info=True)


def get_data_file_abs_path(filename, depth=1):
    """
    :param filename: 获取测试数据文件的绝对路径
    :return:
    """
    file_name = sys._getframe(depth).f_code.co_filename  # 层级调用者所在文件的文件名(全路径)
    func_name = sys._getframe(depth).f_code.co_name  # 层级调用者所在方法的方法名
    file_path = os.path.join(DATA_DIR, 'cases', os.path.splitext(os.path.split(file_name)[-1])[0],
                             func_name, filename)  # cases
    return file_path


@log4gs
def read_excel(filename):
    """
    :param filename: csv文件名
    :return: csv除了title的数据列表
    """
    file_path = get_data_file_abs_path(filename, depth=2)
    excel = xlrd.open_workbook(file_path)
    sheet = excel.sheets()[0]
    title = sheet.row_values(0)
    body = []
    for i in range(1, sheet.nrows):
        row_dict = {}
        for j, d in enumerate(sheet.row_values(i)):
            row_dict[title[j]] = d
        body.append(row_dict)
    return body


@log4gs
def write_excel(filename, results):
    """
    :param result: 回填运行结果
    :return:
    """
    file_path = get_data_file_abs_path(filename, depth=2)
    workbook = open_workbook(file_path)
    write_col = workbook.sheets()[0].ncols - 1
    new_workbook = copy(workbook)
    new_worksheet = new_workbook.get_sheet(0)

    for i, result in enumerate(results):
        write_excel.log.info(result)
        new_worksheet.write(i+1, write_col, result)
    new_workbook.save(file_path)